package logger

import (
	"github.com/sirupsen/logrus"
	"os"
)

type Logger struct {
	name string
	path string
	*logrus.Logger
}

func NewLog(name string, path string, level string) *Logger {
	newLog :=  logrus.New()

	if path == "" {
		newLog.SetOutput(os.Stdout)
	} else {
		f, err := frWrite(path + "/" + name + ".log")
		if err != nil {
			logrus.Errorln("failed to create new log", err)
		} else {
			newLog.SetOutput(f)
		}
	}

	l, err := logrus.ParseLevel(level)
	if err != nil {
		logrus.Panicf("log [%v] level[%v] is not right \n", name, level)
	}
	newLog.SetLevel(l)

	return &Logger{name, path, newLog}
}

var logs = make(map[string]*Logger)

func GetLog(name string) *Logger {
	if !isInit {
		LoadConf("")
	}

	theLog := logs[name]
	if theLog == nil {
		logrus.Warnf("no named [%v] logger, use default logger instead", name)
		theLog = logs["default"]
	}

	return theLog
}

func loadConfigLog() {
	logConf := get("logger", "")
	if logConf == "" {
		logrus.Warnf("no logger configuration here. no log will be create.")
		return
	}

	for k, v := range logConf.(map[interface{}]interface{}) {
		logrus.Debugln(k, v)

		theK := k.(string)
		theV := v.(map[interface{}]interface{})

		name := getString(theV, "name", theK)
		level := getString(theV, "level", "info")

		path := getString(theV, "path", "logs")
		appender := getString(theV, "append", "file")
		if appender == "console" {
			path = ""
		}

		logs[theK] = NewLog(name, path, level)
	}
}

func getString(data map[interface{}]interface{}, key, defaultVal string) string {
	if len(data) == 0 {
		return defaultVal
	}

	theV := data[key]
	if theV == nil {
		return defaultVal
	}

	switch theV.(type) {
	case string:
		return theV.(string)
	default:
		logrus.Panicf("the value[%v -> %v] is not string", key, theV)
	}

	return defaultVal
}

